<template>
  <div id="testlistpanel">
    <vxe-modal :title="`镜检截图`" width="70vw" v-model="dialogFormVisible" draggable destroy-on-close @close='imgUpLoadClose'>
      <el-row class="imgPreview">
        <vxe-toolbar class-name="bg-orange light pandList">
          <template #buttons>
            <span class="padding-lr-xs">
              <vxe-button type="text" content="截取" class-name="padding-lr-xs" class="button-blue padding-lr-xs" @click="begainScreen()" />
            </span>
            <span class="padding-lr-xs">
              <el-upload class="upload-demo" :data="paramData" :headers="headers" :action="uploadFilePath" :show-file-list="false" multiple :on-success="onSuccess" :on-error="onError">
                <vxe-button type="text" content="上传" class-name="padding-lr-xs" class="button-blue padding-lr-xs" @click="upload()" />
              </el-upload>
            </span>
          </template>
        </vxe-toolbar>
        <div class="demo-image__lazy">
          <div class="el-image" style="background-color: #8a919498" @dblclick="begainScreen">
            <canvas id="canvasItem" style="width: calc(100% - 2px); height: calc(100%); z-index: 999" v-show="false"></canvas>
            <video ref="videoEl" id="videoItem" style="width: calc(100% - 2px); height: calc(100%); z-index: 999999"></video>
          </div>
        </div>
      </el-row>
      <div style="height: 160px; overflow-x: auto; width: calc(100% - 2px)">
        <div class="main-img" ref="mainImg" v-loading="loading" style="height: calc(100% - 40px); overflow-x: auto; width: calc(100% - 2px)">
          <ul class="img-box">
            <li v-for="(item, index) in wLFileList" :key="index" :style="{ width: imgWidth + 'px', height: imgHeight + 'px' }">
              <el-image :src="picUrlBase + item.imageUrl" :initial-index="index"></el-image>
              <el-checkbox v-model="item.isSelected" :true-label="1" :false-label="0" @change="(val) => selectFile(val, item)" v-if="resultIsDisabled()" />
              <el-button type="danger" :icon="Delete" circle @click="deleteImg(item)" v-if="resultIsDisabled()" />
            </li>
          </ul>
        </div>
      </div>
    </vxe-modal>
  </div>
  <!-- <ScreenShot v-if="screenshotStatus" @destroy-component="destroyComponent" @get-image-data="getImg"></ScreenShot> -->
</template>
<script setup lang="ts">
import { reactive, ref, getCurrentInstance, onMounted, onBeforeUnmount, inject, defineExpose, defineEmits } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { UploadProps } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import 'vxe-table/lib/style.css';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { SnowflakeHelper } from '@/utils/SnowflakeHelper';

let SnowflakeHelperObj = new SnowflakeHelper(1, 1);
let images: any = reactive([]); //图片信息集合
let isChk = ref(0); //是否审核
let disabled = ref(true);
let uploadDisabled = ref(true);
let deleteDisabled = ref(true);
let picUrlBase = (window as any).apiUrl.VITE_SERVER_URL;
let wLFileList = reactive([]);
let currentFileList = reactive([]); //当前选中的文件数组
let id = ''; //接收传过来的检验结果id
let imgWidth = 132;
let imgHeight = 99; //图片高度，图片宽高比需要为4:3
let loading = false;
let headers = { Authorization: 'Bearer ' + localStorage.getItem('token') };
let dialogFormVisible = ref(false);
let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
let rptImages = inject('rptImages'); /**检验记录当前选中对象 */
let flowNodeGermInfoObj: any = reactive({});/**方案、节点、细菌、菌株等信息对象 */

// 请求参数数据
let paramData: any = reactive({});

//使用 ref 对象来获取 DOM 元素
const videoEl = ref(null);
// 存储拍摄后的图片路径
const imageUrl = ref<string | null>(null);
const pictureUrl = ref<string>((window as any).apiUrl.VITE_SERVER_URL + '/image/');
const picture = ref(null);

defineExpose({
  initPage
});

const proxyEmit = defineEmits(['updateTestList']);

onMounted(() => {
  //getImage();
});

// 上传图片 弹框
function upload() {
  paramData.id = '';
  paramData.rptGroup = labMainInfoObj.rptGroup;
  paramData.sampleda = formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00');
  paramData.sampleNo = labMainInfoObj.sampleNo;
  //fixme:20241206解决镜检上传图片无法查询获取的问题，没搞懂逻辑先临时解决
  paramData.testFlowNo = IsEmpty(flowNodeGermInfoObj.testFlowNo) ? null : flowNodeGermInfoObj.testFlowNo,
  paramData.testNodeNo = IsEmpty(flowNodeGermInfoObj.testNodeNo) ? null : flowNodeGermInfoObj.testNodeNo,
  paramData.isolateNum = IsEmpty(flowNodeGermInfoObj.isolateNum) ? null : flowNodeGermInfoObj.isolateNum
}
// 上传成功
function onSuccess(e: any) {
  if (e && e.status && e.status.code && e.status.code === 400) {
    VxeMessage(e.status.msg.replace('IOException: ', ''), VxeNotifyType.error);
    return;
  }
  getImage();
}
//上传失败
function onError(e: any) {
  console.log('失败', e);
}

async function deleteImg(item: any) {
  handleDelete(item);
}
//关闭窗口时出发
async function imgUpLoadClose() {
  dialogFormVisible.value = false;
  proxy.$emit('loadImgsCallback');
}
//删除
async function handleDelete(item: any) {
  const url = '/api/bac/bac-image-result/deleteBacImageResult';
  proxy.$http.post(url, item).then((res: any) => {
    if (res.status.code === 1) {
      VxeMessage('删除成功', VxeNotifyType.success);
      getImage();
    } else {
      VxeMessage('删除失败', VxeNotifyType.error);
    }
  });
}

function initPage(mainInfoRow: any, detailInfoObj: any) {
  dialogFormVisible.value = true;
  Object.assign(labMainInfoObj, mainInfoRow);
  Object.assign(flowNodeGermInfoObj, detailInfoObj);
  getImage();
  clearPhoto();
  checkCamera();
}

// 获取图片
function getImage() {
  disabled.value = true;
  currentFileList.length = 0;
  wLFileList.length = 0;
  const url = '/api/bac/bac-image-result/findBacImageResultList';
  paramData.rptGroup = labMainInfoObj.rptGroup;
  paramData.sampleda = formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd hh:mm:ss');
  paramData.sampleNo = labMainInfoObj.sampleNo;
  proxy.$http
    .get(url, {
      params: {
        rptGroup: paramData.rptGroup,
        sampleda: formatDateTime(paramData.sampleda, 'yyyy-MM-dd 00:00:00'),
        sampleNo: paramData.sampleNo,
        testFlowNo: IsEmpty(flowNodeGermInfoObj.testFlowNo) ? null : flowNodeGermInfoObj.testFlowNo,
        testNodeNo: IsEmpty(flowNodeGermInfoObj.testNodeNo) ? null : flowNodeGermInfoObj.testNodeNo,
        isolateNum: IsEmpty(flowNodeGermInfoObj.isolateNum) ? null : flowNodeGermInfoObj.isolateNum
      }
    })
    .then(async (res: any) => {
      if (!IsEmpty(res.data) && res.data) {
        Object.assign(wLFileList, res.data);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 选中文件
function selectFile(isselected: number, val: any) {
  updateImagesChecked(val);
}

function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return false;
  } else {
    return true;
  }
}

//取消检验图片保存到图文
async function updateImagesChecked(item: any) {
  const url = '/api/bac/bac-image-result/updateBacImageResult';
  proxy.$http
    .post(url, item)
    .then((res: any) => {
      if (res.status.code === 1) {
        proxy.$emit('SelectedCallback');
        VxeMessage(`${item.isSelected === 1 ? '选中' : '取消选中'}操作完成`, VxeNotifyType.success);
      } else {
        VxeMessage(`${item.isSelected === 1 ? '选中' : '取消选中'}操作失败`, VxeNotifyType.error);
        item.isSelected = IsEmpty(item.isSelected) ? 0 : item.isSelected === 1 ? 0 : 1;
      }
    });
}

// 上传图片
const uploadFilePath = ref((window as any).apiUrl.VITE_SERVER_URL + '/api/bac/bac-image-result/uploadImage');

const clearPhoto = () => {
  picture.value = picture.value = null;
  //获得Canvas对象
  const canvas: any = document.getElementById('canvasItem');
  if (canvas) {
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, 200, 200);
  }
};

// 拍摄函数，截取摄像头当前帧并显示在页面上
function begainScreen() {
  clearPhoto();
  // 检查视频元素和页面容器是否存在
  if (!videoEl.value) return;
  setTimeout(async () => {
    const canvas: any = document.getElementById('canvasItem');
    if (canvas) {
      canvas.width = (videoEl.value as any).videoWidth;
      canvas.height = (videoEl.value as any).videoHeight;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(videoEl.value, 0, 0, canvas.width, canvas.height);
      picture.value = canvas.toDataURL('image/png');
      setTimeout(() => {
        uploadImage();
      }, 50);
    }
  }, 50);
}

// 检查摄像头并设置视频流
async function checkCamera() {
  if (!videoEl.value) {
    setTimeout(() => {
      checkCamera();
    }, 200);
    return;
  }
  clearPhoto();
  const navigator = window.navigator.mediaDevices;
  const devices = await navigator.enumerateDevices();
  // 如果存在媒体设备，获取摄像头视频流
  if (devices) {
    // 请求用户媒体设备（摄像头）
    const stream = await navigator.getUserMedia({
      audio: false,
      video: {
        width: (videoEl.value as any).videoWidth, // 设置视频宽度
        height: (videoEl.value as any).videoHeight, // 设置视频高度
        facingMode: 'user' // 使用前置摄像头
      }
    });
    // 如果视频元素存在，将视频流绑定到视频元素上并开始播放
    if (videoEl.value) {
      (videoEl.value as any).srcObject = stream;
      (videoEl.value as any).play();
    }
  }
}

const uploadImage = async () => {
  if (picture.value) {
    const response = await fetch(picture.value);
    const blob = await response.blob();
    let formData = new FormData();
    formData.append('id', SnowflakeHelperObj.nextId());
    formData.append('rptGroup', paramData.rptGroup);
    formData.append('sampleda', paramData.sampleda);
    formData.append('sampleNo', paramData.sampleNo);

    formData.append('testFlowNo', IsEmpty(flowNodeGermInfoObj.testFlowNo) ? null : flowNodeGermInfoObj.testFlowNo);
    formData.append('testNodeNo', IsEmpty(flowNodeGermInfoObj.testNodeNo) ? null : flowNodeGermInfoObj.testNodeNo);
    formData.append('isolateNum', IsEmpty(flowNodeGermInfoObj.isolateNum) ? null : flowNodeGermInfoObj.isolateNum);
    const seqNum = formatDateTime(new Date(), 'yyyyMMddhhmmss');
    formData.append('seq', (IsEmpty(seqNum) ? (wLFileList.length + 1) + '' : seqNum) as string);
    formData.append('germNo', IsEmpty(flowNodeGermInfoObj.germNo) ? null : flowNodeGermInfoObj.germNo);
    formData.append('isSelected', '0');

    formData.append('file', blob);
    try {
      const uploadResponse = await fetch(uploadFilePath.value, {
        method: 'POST',
        body: formData,
        headers: headers
      });
      getImage();
      clearPhoto();
    } catch (error) {
      console.error('网络请求错误', error);
    }
  }
};
</script>
<style lang="scss" scoped>
#testlistpanel {
  height: 100%;
  // 附加按钮间距
  //.button-red {
  //  margin: 5px 0 0 5px;
  //}
  // 中间table表格

  .demo-image__lazy {
    float: inline-end;
    width: calc(100% - 0px);
    height: calc(100vh - 260px);
    overflow: auto;
  }

  .el-image {
    display: block;
    min-width: calc(100% - 80px);
    margin-bottom: 10px;
    overflow-x: auto;
    height: calc(100% - 10px);
  }

  .demo-image__lazy .el-image:last-child {
    margin-bottom: 0;
  }

  .imgPreview {
    height: calc(100vh - 260px);
  }

  .pandList {
    text-align: center;
    z-index: 999;
    position: absolute;
    background: unset;
  }

  img:hover {
    transform: scale(1.2);
  }

  :deep(.vxe-body--row) {
    height: 80px;
  }

  .el-checkbox {
    position: absolute;
    top: 5px;
    left: 6px;
  }

  .el-link {
    position: absolute;
    top: 0px;
    right: 0px;

    i {
      margin-right: -2px;
      font-size: 16px;
    }
  }

  .main-img {
    ul.img-box {
      margin: 0;
      padding: 0;
      list-style-type: none;
      overflow: auto;

      > li {
        position: relative;
        display: inline; //让li横向排列
        padding: 5px;
        float: left;
      }

      .el-image {
        width: 132px;
        height: 99px;
        border: 1px #aaa solid;
        box-sizing: border-box;
      }

      .el-checkbox {
        position: absolute;
        top: 0px;
        left: 6px;
      }

      .el-button {
        position: absolute;
        top: 0px;
        right: 0px;
      }

      .el-link {
        position: absolute;
        top: 0px;
        right: 0px;

        i {
          margin-right: -2px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>
